import json
import logging
import socket
import struct
import sys
import threading
import time

from handlers.connection import connection
from handlers.register import register
from main import ip_config_func, collect_func, config_test
from utils.decorator import async_func
from utils.enums import OperationEnum, CollectEnum, RegisterTypeEnum

a = b'U\x07\x00\x00\x1d\x02\x00\x01\x00\x00\x00\x00M6F-D070-20220523-002\x00,\xf4'

HOST, PORT = "localhost", 6802
lock = threading.Lock()
logger = logging.getLogger(__name__)


class TCPConn:

    def __init__(self):
        self.connect()
        self.send_count = 0
        self.inited = False

    def connect(self):
        while True:
            try:
                with lock:
                    self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    self.conn.connect((HOST, PORT))
                    break
            except Exception as e:
                print(f'reconnect error, msg: {e.args}')
                time.sleep(0.2)

    @async_func
    def read(self):
        while True:
            try:
                received = self.conn.recv(1024)
                logger.info(f'client received: {received}')
                # print("Received: {}".format(received))
            except socket.error as e:
                self.inited = False
                print(e.args)

    @async_func
    def write(self):
        while True:
            try:
                if not self.inited:
                    self.conn.sendall(a)
                    self.inited = True
            except socket.error as e:
                self.inited = False
                print('write error: ', e.args)
                self.connect()

    def _third(self, conn):
        received = conn.recv(1024)
        print("Received: {}".format(received))
        time.sleep(0.2)


def console():
    print("*" * 50, '网络调试小助手', '*' * 50)
    print('1: 配置IP\n2: 数据采集\n3: 当前活动设备\n4: SN配置\n5: 量程配置\n6: 频率配置\n7: 退出')
    print("*" * 50, 'END OF', '*' * 50)


def main():
    while True:
        console()
        cmd = input('请输入指令：')
        num = None
        try:
            cmd = cmd.split(' ')
            num = int(cmd[0])
            if num not in OperationEnum.valid_enums():
                print(f'操作: {num}, 不是有效操作, 请重试')
                continue
        except Exception:
            print(f'错误的操作: {num}, 请重试')
            continue
        else:
            if num == OperationEnum.IP_CONFIG:
                ip_config_func()
            elif num == OperationEnum.DATA_COLLECT:
                collect_func()
            elif num == OperationEnum.LIVE_HREF:
                print('IP配置链接: ')
                for i in connection.allowed:
                    print(f'{i}: {i.sn}')
                print('活动链接: ')
                for k, v in connection.alive_handler_dict.items():
                    print(f'设备SN: {k}, 采集状态: {CollectEnum.get_collect_desc(v["collect"])}')
            elif num == OperationEnum.SN:
                old = input('请输入旧SN: ')
                new = input('请输入新SN: ')
                register.start(cat=RegisterTypeEnum.CONFIG, command='sn', data=dict(sn=old, dest=new))
            elif num == OperationEnum.MEASUREMENT:
                sn = input("请输入设备SN: ")
                m = input('请输入量程百分比选项(1：100%；2：50%；3：25%(默认值)；4：12.5%): ')
                register.start(cat=RegisterTypeEnum.CONFIG, command='measurement', data=dict(sn=sn, m=m))
            elif num == OperationEnum.HZ:
                pass
            else:
                break
    print('server exit')


if __name__ == '__main__':

    # source = 'M6F-D070-20220523-002'
    #
    # ins = TCPConn()
    # ins.write()
    # ins.read()
    #
    # main()

    a = config_test(sn='M6F-D070-20220523-001', m=1)
    print(a)
    # register.start(cat=RegisterTypeEnum.CONFIG, command='measurement', data=dict(sn='M6F-D070-20220523-001', m=1))



